package com.agrm.rabc.controller;


import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.PermResourceMapping;
import com.agrm.rabc.service.PermResourceMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api/v1/perm_resources", produces = MediaType.APPLICATION_JSON_VALUE)
public class PermResourceMappingApi {
    private PermResourceMappingService permResourceMappingService;

    @Autowired
    public void setPermResourceMappingService(PermResourceMappingService permResourceMappingService) {
        this.permResourceMappingService = permResourceMappingService;
    }

    @GetMapping
    public ResponseResult findAll(PermResourceMapping prm) {
        List<PermResourceMapping> mappings = permResourceMappingService.findAll(prm);
        return ResponseResult.okResult(mappings);
    }

    @GetMapping("/id/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        PermResourceMapping prm = permResourceMappingService.findById(id);
        if (prm == null) {
            return ResponseResult.errorResult(-1,"未查询到指定编号的权限-资源关联");
        } else {
            return ResponseResult.okResult(prm);
        }
    }

    @PostMapping
    public ResponseResult save(@RequestBody PermResourceMapping prm) {
        boolean success = permResourceMappingService.save(prm);
        if (success) {
            return ResponseResult.okResult(200,"保存成功！");
        } else {
            return ResponseResult.errorResult(-1,"保存权限-资源关联失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody PermResourceMapping prm) {
        boolean success = permResourceMappingService.update(prm);
        if (success) {
            return ResponseResult.okResult(200,"更新成功！");
        } else {
            return ResponseResult.errorResult(-1,"修改权限-资源关联失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        Objects.requireNonNull(ids);
        int count = permResourceMappingService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除权限-资源关联失败");
        }
    }
}
